import 'dart:async';
import 'package:bookshelf/util/toast_util.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import '../entity/setting_entity.dart';
import '../event/inventory_event.dart';
import '../main.dart';
import '../socket/send_helper.dart';


class Test extends StatefulWidget {
  const Test({Key? key}) : super(key: key);

  @override
  State<Test> createState() => _TestState();
}

class _TestState extends State<Test> {


  List<SettingEntityReader> readers = [];
  var inventoryIndex = 0;
  StreamSubscription? inventorySubscription;
  Timer? _inventoryTimer;

  RxInt inventoryTime = 0.obs;
  RxInt successTime = 0.obs;

  bool isStart = false;

  @override
  initState() {
    super.initState();

    inventorySubscription = eventFactory.on<InventoryEvent>().listen((event) {

      inventoryIndex++;
      _inventory();
    });



  }


  _inventory(){
    if(inventoryIndex<readers.length){
      hfSerialPortHelper.sendData(inventoryAll(readers[inventoryIndex].station!));
    }else{
      successTime.value = successTime.value+1;
    }
  }

  _startInventory(){
    if(settingEntity.reader != null){
      for (var element in settingEntity.reader!) {
        if(element.state == 0){
          readers.add(element);
        }
      }
      if(readers.isEmpty){
        return;
      }
      _inventoryTimer = Timer.periodic(Duration(seconds:settingEntity.inventoryTime??30), (timer) async {
        inventoryIndex = 0;
        _inventory();
        inventoryTime.value = inventoryTime.value +1;
      });
    }
  }


  @override
  void dispose() {
    inventorySubscription?.cancel();
    inventorySubscription = null;
    _inventoryTimer?.cancel();
    _inventoryTimer = null;
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        resizeToAvoidBottomInset: false,
        appBar: AppBar(
          title: const Text("测试"),
          leading: IconButton(
            icon: const Icon(Icons.arrow_back_ios),
            onPressed: (){
              Get.back();
            },
          ),
        ),
        body: Column(
          children: [
            InkWell(
              onTap: (){
                if(!isStart){
                  isStart = true;
                  _startInventory();
                }else{
                  toastWarn('已经开始');
                }

              },
              child:  Text(' 开始测试 ', style: TextStyle(fontSize: 8.sp,color: Colors.blue)),
            ),
            Obx(() => Text('盘点总次数: ${ inventoryTime.value}')),
            Obx(() => Text('盘点成功次数: ${ successTime.value}')),
          ],
        )
    );
  }
}